package eerbaar.collision.internal;

import eerbaar.elements.IElement;
import eerbaar.elements.extension.ILeaderElement;
import eerbaar.elements.extension.IPackMemberElement;
import eerbaar.position.IPosition;
import eerbaar.position.IPositionListener;
import eerbaar.position.WrongPositionException;

public class PackWatcher {

    private final IPackMemberElement member;
    private final ILeaderElement leader;

    private final IPositionListener listener = new IPositionListener() {

        @Override
        public void afterPositionChange(IPosition oldPos, IPosition p) {
            PackWatcher.this.afterPositionChange(p);
        }

        @Override
        public void beforePositionChange(IPosition pos)
                throws WrongPositionException {
        }

    };

    public PackWatcher(IPackMemberElement member, ILeaderElement leader) {
        this.member = member;
        this.leader = leader;
        start();
    }

    private void afterPositionChange(IPosition p) {
        double d = distance();
        if (d > 2.5) {

            // DisplayRisingTextMsg msg = new DisplayRisingTextMsg("Leave Pack",
            // p.getX(), p.getY(), Color.ALICE_BLUE);
            // MsgHelper.sendMsg(DisplayRisingTextMsg.class, msg);

            this.leader.remove(this.member);
            {
                IElement e = this.member.getExtension(IElement.class);
                e.getPosition().removeListener(this.listener);
            }
            {
                IElement e = this.leader.getExtension(IElement.class);
                e.getPosition().removeListener(this.listener);
            }
        }
    }

    private double distance() {
        IElement e1 = this.member.getExtension(IElement.class);
        IElement e2 = this.leader.getExtension(IElement.class);
        double x1 = e1.getPosition().getX();
        double y1 = e1.getPosition().getY();
        double x2 = e2.getPosition().getX();
        double y2 = e2.getPosition().getY();
        return Math.sqrt(((x1 - x2) * (x1 - x2)) + ((y1 - y2) * (y1 - y2)));
    }

    private void start() {
        {
            IElement e = this.member.getExtension(IElement.class);
            e.getPosition().addListener(this.listener);
        }
        {
            IElement e = this.leader.getExtension(IElement.class);
            e.getPosition().addListener(this.listener);
        }
    }

}
